import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

public class Transfer extends JPanel implements ActionListener {
    private ATM frame;
    private Icon bgOff = Util.getIcon("/images/buttonOff.jpg");
    private Icon bgsure = Util.getIcon("/images/buttonSure.jpg");
    private JButton offButton = new JButton(bgOff);
    private JButton sureButton = new JButton(bgsure);
    private JTextField textField = new JTextField();
    private JTextField textFieldNew = new JTextField();

    public Transfer(ATM frame) {
        this.frame = frame;
        this.setLayout(null);
        this.setOpaque(false);
        sureButton.setBounds(300, 500, 100, 50);
        this.add(sureButton);
        sureButton.addActionListener(this);
        offButton.setBounds(300, 600, 100, 50);
        this.add(offButton);
        offButton.addActionListener(this);
        JLabel label = new JLabel("输入账户");
        label.setBounds(350, 300, 150, 20);
        this.add(label);
        textField.setBounds(500, 300, 100, 20);
        this.add(textField);
        JLabel labelNew = new JLabel("输入金额");
        labelNew.setBounds(350, 400, 150, 20);
        this.add(labelNew);
        textFieldNew.setBounds(500, 400, 100, 20);
        this.add(textFieldNew);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == sureButton){
            // 获取输入的对方账号
            String otherAccount = textField.getText();
            double blance = 0;
            try {
                // 获取输入的转账金额
                blance = Double.parseDouble(textFieldNew.getText());
            }catch(NumberFormatException ex){
                JOptionPane.showMessageDialog(this,"转账金额必须为数字，并不能为空");
                return;
            }

            // 当期登录的账户
            Util db = new Util();
            User loginUser = db.getById(frame.getLoginUser().getId());
            User otherUser = db.getByUsername(otherAccount);
            // 判断账号是否存在
            if(otherUser == null){
                JOptionPane.showMessageDialog(this,"查无此人");
                return;
            }
            // 判断是否转给自己
            if(loginUser.getName().equals(otherAccount)){
                JOptionPane.showMessageDialog(this,"不能转给自己");
                return;
            }
            // 判断余额是否足够
            if(blance > loginUser.getMoney()){
                JOptionPane.showMessageDialog(this,"余额不足");
                return;
            }
            // 当期账户扣钱
            loginUser.setMoney(loginUser.getMoney() - blance);
            // 对方账户加钱
            otherUser.setMoney(otherUser.getMoney() + blance);
            db.update(loginUser,otherUser);
            JOptionPane.showMessageDialog(this,"转账成功");
            frame.switchPanel("menu");
        }else if(e.getSource() == offButton){
            frame.switchPanel("menu");

        }
    }
}

